package com.stores.action;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.stores.model.CloudDb;
import com.stores.model.Manufacturer;

public class ManageManufacturerAction {

	/***
	 * 
	 * @param mfg
	 */
	public void Create(Manufacturer mfg) {
		this.createUpdate(mfg, (short) 0);
	}

	/**
	 * 
	 * @param mfg
	 * @param id
	 */
	private void createUpdate(Manufacturer mfg, short id) {
		try {
			CloudDb db = new CloudDb();
			Connection connection = db.getConnection();
			CallableStatement query = connection
					.prepareCall("call ionlinestores.createUpdateMfg(?,?,?,?,?,?)");
			query.setShort(1, id);
			query.setString(2, mfg.getName());
			query.setString(3, mfg.getDescription());
			query.setString(4, mfg.getSmallImage());
			query.setString(5, mfg.getMediumImage());
			query.setString(6, mfg.getLargeImage());
			query.execute();
			connection.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param category
	 * @return
	 */
	public boolean Update(Manufacturer mfg) {
		this.createUpdate(mfg, (short) mfg.getMfgId());
		return true;
	}

	/**
	 * 
	 * @return
	 */
	public List<Manufacturer> Retrive() {
		List<Manufacturer> manufacturers = new ArrayList<Manufacturer>();
		try {
			CloudDb db = new CloudDb();
			Connection connection = db.getConnection();
			StringBuilder query = new StringBuilder();
			query.append("select mfgId, mfgName, mfgDescription, smallLogoUrl, mediumLogoUrl, largeLogoUrl from manufacturer;");
			CallableStatement statement = connection.prepareCall(query
					.toString());
			ResultSet queryResult = statement.executeQuery();
			
			while(queryResult.next()){
				Manufacturer m = new Manufacturer();
				m.setMfgId((int)queryResult.getShort(1));
				m.setName(queryResult.getString(2));
				m.setDescription(queryResult.getString(3));
				m.setSmallImage(queryResult.getString(4));
				m.setMediumImage(queryResult.getString(5));
				m.setLargeImage(queryResult.getString(6));
				manufacturers.add(m);
			}
			connection.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return manufacturers;
	}

}
